package com.ewing.busi.order.service;

import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import com.ewing.busi.base.service.BaseService;
import com.ewing.busi.order.dao.OrderDetailDao;
import com.ewing.busi.order.dto.OrderInfoDetailResp;
import com.ewing.busi.order.model.OrderDetail;
import com.ewing.busi.resource.dao.WebResourcePriceDao;
import com.ewing.busi.resource.dao.WebResourceSpecDao;
import com.ewing.busi.resource.model.WebResourcePrice;
import com.ewing.busi.resource.model.WebResourceSpec;
import com.ewing.busi.seller.service.SellerShopService;
import com.ewing.utils.FileUrlUtil;
import com.google.common.collect.Lists;

@Repository("orderDetailService")
public class OrderDetailService extends BaseService {

  @Resource
  private OrderDetailDao orderDetailDao;
  @Resource
  private WebResourcePriceDao webResourcePriceDao;
  @Resource
  private WebResourceSpecDao webResourceSpecDao;
  @Resource
  private SellerShopService sellerShopService;

  public List<OrderInfoDetailResp> findByOrderIdAndCusId(Integer orderId, Integer cusId, Integer shopId) {
    if (null == orderId) {
      return Collections.emptyList();
    }

    List<OrderInfoDetailResp> list = orderDetailDao.findByOrderIdAndCusId(orderId, cusId);
    String shopName = sellerShopService.findName(shopId);
    for (OrderInfoDetailResp resp : list) {
      resp.setIcon(FileUrlUtil.convertResourceUrl(resp.getIcon()));
      resp.setSpecs(StringUtils.join(findOrderSpec(cusId, resp.getId()).toArray(), "，"));
      resp.setShopName(shopName);
    }
    return list;
  }

  public OrderDetail findByIdAndCusId(Integer id, Integer cusId) {
    if (null == id) {
      return null;
    }

    return orderDetailDao.findByIdAndCusId(id, cusId);
  }


  public List<String> findOrderSpec(Integer cusId, Integer detailId) {
    if (null == detailId) {
      return Collections.emptyList();
    }

    OrderDetail detail = orderDetailDao.findByIdAndCusId(detailId, cusId);
    if (null == detail) {
      return Collections.emptyList();
    }
    WebResourcePrice price = webResourcePriceDao.findById(detail.getPriceId());
    if (null == price || StringUtils.isEmpty(price.getSpecIds())) {
      return Collections.emptyList();
    }

    List<Integer> ids = Lists.newArrayList();
    for (String id : price.getSpecIds().split(",")) {
      ids.add(Integer.valueOf(id));
    }
    List<WebResourceSpec> specList = webResourceSpecDao.findByIds(ids);
    List<String> result = Lists.newArrayListWithExpectedSize(specList.size());
    for (WebResourceSpec spec : specList) {
      result.add(spec.getRootSpec() + ":" + spec.getSpec());
    }
    return result;
  }

}
